<template>
  <div>
    <div class="search-container">
      <div class="search-inp-container">
        <el-input @keyup.enter.native="handleSearch" placeholder="请输入手机号码" v-model="listQuery.mobile" clearable>
        </el-input>
      </div>
      <div class="search-inp-container">
      <el-input @keyup.enter.native="handleSearch" placeholder="请输入用户名" v-model="listQuery.username" clearable>
      </el-input>
      </div>
      <el-button class="search-btn" type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
      <el-button class="search-btn" type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
      <el-button class="search-btn" icon="el-icon-delete" @click="handleBatchDeleteDict">批量删除</el-button>
      <el-button class="search-btn" :autofocus="true" icon="el-icon-refresh" @click="refreshHandle">刷新</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row ref="multipleTable" tooltip-effect="dark">
      <el-table-column type="selection" width="80" align="center">
      </el-table-column>
      <el-table-column align="center" prop="username" label="用户名" width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" prop="realName" label="姓名" width="100" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" prop="mobile" label="手机号">
      </el-table-column>
      <el-table-column align="center" label="角色">
        <template slot-scope="scope">
          <span v-for="role in scope.row.sysRoleVoList" :key="role.roleCode">{{role.roleName}} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属机构">
        <template slot-scope="scope">
            {{findOrgNameByorgId(scope.row.orgId)}}
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" width="60">
        <template slot-scope="scope">
          {{scope.row.status | statusFilter}}
<!--          <el-tag v-if="scope.row.status == 0">-->
<!--            {{scope.row.status | statusFilter}}-->
<!--          </el-tag>-->
<!--          <el-tag v-else type="danger">-->
<!--            {{scope.row.status | statusFilter}}-->
<!--          </el-tag>-->
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="300px" v-if="sys_user_update  || sys_user_delete ">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === '0'" size="mini" type="success" @click="updateStatus(scope.row,'1')" style="margin-left:2px;margin-top:2px">停用</el-button>
          <el-button v-if="scope.row.status === '1'" size="mini" type="success" @click="updateStatus(scope.row,'0')" style="margin-left:2px;margin-top:2px">启用</el-button>
          <el-button v-if="sys_user_update" size="mini" type="primary" @click="handleEdit(scope.row)" style="margin-left:2px;margin-top:2px">编辑</el-button>
          <el-button v-if="sys_user_reset" size="mini" type="primary" @click="handleReset(scope.row)" style="margin-left:2px;margin-top:2px">重置密码</el-button>
          <el-button v-if="sys_user_delete" size="mini" type="danger" @click="handleDelete(scope.row)" style="margin-left:2px;margin-top:2px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.current" :page-size="listQuery.size" :page-sizes="[10, 40, 80, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" width="40%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input class="w347" v-model="form.username" placeholder="请输用户名"></el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="realName">
          <el-input class="w347" v-model="form.realName" placeholder="请输姓名"></el-input>
        </el-form-item>

        <el-form-item class="w347" v-if="dialogStatus == 'create'" label="密码" placeholder="请输入密码" prop="password">
          <el-input type="password"  v-model="form.password"></el-input>
        </el-form-item>

        <el-form-item label="所属机构" prop="orgId">
          <el-select class="filter-item w347" v-model="form.orgId" placeholder="请选择">
            <el-option v-for="item in orgList" :key="item.orgId" :label="item.orgName" :value="item.orgId"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select class="filter-item w347" v-model="form.role" placeholder="请选择" multiple @input="change($event)">
            <el-option v-for="item in rolesOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" :disabled="isDisabled[item.delFlag]">
              <span style="float: left">{{ item.roleName }}</span>
              <!--<span style="float: right; color: #8492a6; font-size: 13px">{{ item.roleCode }}</span>-->
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input class="w347" v-model="form.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="状态" v-if="dialogStatus == 'update' && sys_user_delete " prop="delFlag">
          <el-select class="filter-item w347" v-model="form.status" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item" :label="item | statusFilter" :value="item"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="reMark">
          <el-input type="textarea" :rows="2" v-model="form.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" :close-on-click-modal="false" :visible.sync="resetPassDialogFormVisible" width="40%">
      <el-form :model="resetPassFrom" :rules="resetPassRules" ref="resetPassFrom" label-width="100px">

        <el-form-item class="w347" label="新密码" placeholder="请输入新密码" prop="newPassword">
          <el-input type="password"  v-model="resetPassFrom.newPassword"></el-input>
        </el-form-item>

        <el-form-item class="w347" label="确认新密码" placeholder="请输入新密码" prop="confirmNewPassword">
          <el-input type="password"  v-model="resetPassFrom.confirmNewPassword"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelResetPassFrom('resetPassFrom')">取 消</el-button>
        <el-button type="primary" @click="reSetPass('resetPassFrom')">修 改</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, delObj, getObj, addObj, putObj, putPass } from '@/api/user'
import { listRoleInfoByUserId } from '@/api/role'
import { mapGetters } from 'vuex'
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!(/\d/.test(value))) {
        callback(new Error('密码需包含字母以及数字，密码长度在 8 到 20 个字符'))
      } else if (!(/[a-z]/.test(value))) {
        callback(new Error('密码需包含字母以及数字，密码长度在 8 到 20 个字符'))
      } else {
        callback()
      }// else if (!(/\W/.test(value))) { // 特殊字符
      //   callback(new Error('密码需包含大写、小写以及数字'))
      // }
    }
    const validateConfirmNewPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (this.resetPassFrom.newPassword === undefined) {
        this.$refs.resetPassFrom.validateField('newPassword')
      } else if (value !== this.resetPassFrom.newPassword) {
        callback(new Error('两次输入的密码不一致!'))
      } else {
        callback()
      }
    }

    const validateRole = (rule, value, callback) => {
      debugger
      if (value.length == 0) {
        debugger
        callback(new Error('请再次输入密码'))
      }  else {
        callback()
      }
    }
    return {
      tableKey: 0,
      listLoading: false,
      list: [],
      orgList: [],
      listQuery: {
        current: 1,
        size: 10,
        mobile: '',
        username: '',
        descs: 'create_time'
      },
      total: 0,
      sys_user_add: false,
      sys_user_update: false,
      sys_user_delete: false,
      sys_user_select: false,
      sys_user_reset: false,
      dialogFormVisible: false,
      form: {
        username: undefined,
        realName: undefined,
        password: undefined,
        isValid: undefined,
        mobile: undefined,
        orgId: undefined,
        remark: undefined,
        status: undefined,
        role: []
      },
      resetPassFrom: {
        userId: undefined,
        newPassword: '',
        confirmNewPassword: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入账户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '账号长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        realName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 255,
            message: '账号长度在 1 到 255 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 8,
            max: 20,
            message: '密码需包含字母以及数字，密码长度在 8 到 20 个字符',
            trigger: 'blur'
          },
          {
            validator: validatePass,
            trigger: 'blur'
          }
        ],
        deptId: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'blur'
          }
        ],
        role: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'change',
            //validator: validateRole
          }
        ],
        mobile: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          },
          {
            min: 11,
            max: 11,
            message: '手机号长度为11',
            trigger: 'blur'
          }
        ],
        orgId: [
          {
            required: true,
            message: '请选择行社',
            trigger: 'blur'
          }
        ]
      },
      resetPassRules: {
        newPassword: [
          {
            required: true,
            message: '请输入新密码',
            trigger: 'blur'
          },
          {
            min: 8,
            max: 20,
            message: '密码需包含字母以及数字，密码长度在 8 到 20 个字符',
            trigger: 'blur'
          },
          {
            validator: validatePass,
            trigger: 'blur'
          }
        ],
        confirmNewPassword: [
          {
            required: true,
            message: '请再次输入新密码',
            trigger: 'blur'
          },
          {
            min: 8,
            max: 20,
            message: '密码需包含字母以及数字，密码长度在 8 到 20 个字符',
            trigger: 'blur'
          },
          {
            validator: validateConfirmNewPass,
            trigger: 'blur'
          }
        ]
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogStatus: '',
      role: [],
      rolesOptions: [],
      isDisabled: {
        0: false,
        1: true
      },
      statusOptions: ['0', '1'],
      dialogDeptVisible: false,
      resetPassDialogFormVisible: false,
      treeDeptData: [],
      checkedKeys: [],
      defaultProps: {
        children: 'childrens',
        label: 'name'
      }
    }
  },

  components: {},
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '有效',
        1: '停用',
        9: '锁定'
      }
      return statusMap[status]
    },
    orgNameFilter(orgId) {
      for (let i = 0; i < this.orgList.length; i++) {
        if (orgId === this.orgList[i].orgId) {
          return this.orgList[i].orgName
        }
      }
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },

  mounted() {
    this.getList()
    this.getOrgList()
    this.sys_user_add = this.permissions['/admin/user:add']
    this.sys_user_update = this.permissions['/admin/user:update']
    this.sys_user_delete = this.permissions['/admin/user:delete']
    this.sys_user_select = this.permissions['/admin/user:select']
    this.sys_user_reset = this.permissions['/admin/user:reset']
  },

  methods: {
    getList() {
      this.getOrgList()
      this.getRoleList()
      this.listLoading = true
      this.listQuery.isAsc = false
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    change(e) {
      this.$forceUpdate()
    },
    refreshHandle() {
      this.listQuery.current = 1
      this.listQuery.size = 10
      this.listQuery.mobile = ''
      this.getList()
    },
    handleAdd() {
      this.dialogStatus = 'create'
      this.getRoleList()
      this.setFormEmpty()
      this.dialogFormVisible = true
    },
    handleDelete(row) {
      this.$confirm(
        '此操作将永久删除该用户(用户名:' + row.username + '), 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        delObj(row.userId)
          .then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .cache(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          })
      })
    },
    handleReset(row) {
      this.resetPassFrom.userId = row.userId
      this.resetPassDialogFormVisible = true
    },
    handleEdit(row) {
      // this.dialogStatus = 'update'
      this.getRoleList()
      this.getOrgList()
      this.$forceUpdate()
      getObj(row.userId).then(response => {
        this.form = response.data
        // this.dialogFormVisible = true
        this.dialogStatus = 'update'
        this.role = []
        for (var i = 0; i < row.sysRoleVoList.length; i++) {
          this.role[i] = row.sysRoleVoList[i].roleId
        }
        // this.form.role = this.role
        this.$set(this.form, 'role', this.role)
        this.dialogFormVisible = true
      })
    },
    handleSearch() {
      this.listQuery.current = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },
    create(formName) {
      const set = this.$refs
      this.form.sysRoleVoList = []
      this.form.role.forEach(roleId => {
        const roleInfo = {
          roleId: roleId
        }
        this.form.sysRoleVoList.push(roleInfo)
      })
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form).then(() => {
            this.rolesOptions = []
            this.setFormEmpty()
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.setFormEmpty()
    },
    cancelResetPassFrom(formName) {
      this.resetPassDialogFormVisible = false
      this.resetPassFrom.userId = undefined
      this.resetPassFrom.newPassword = ''
      this.resetPassFrom.confirmNewPassword = ''
    },
    update(formName) {
      const set = this.$refs
      this.bindRoleInfo()
      //this.$refs.ruleForm.resetFields()
      this.form.role
      this.$forceUpdate()
      this.form.role
      debugger
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          this.form.password = undefined
          putObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    reSetPass(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          putPass(this.resetPassFrom).then(() => {
            this.resetPassFrom.userId = undefined
            this.resetPassFrom.newPassword = ''
            this.resetPassFrom.confirmNewPassword = ''
            this.resetPassDialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '密码重置成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    async getRoleList() {
      const res = await listRoleInfoByUserId()
      this.rolesOptions = res.data
    },
    async getOrgList() {
      const res = await fetchOrgList()
      this.orgList = res.data
    },
    bindRoleInfo() {
      this.form.sysRoleVoList = []
      this.form.role.forEach(roleId => {
        const roleInfo = {
          roleId: roleId
        }
        this.form.sysRoleVoList.push(roleInfo)
      })
    },
    findOrgNameByorgId(orgId) {
      for (let i = 0; i < this.orgList.length; i++) {
        // eslint-disable-next-line eqeqeq
        if (orgId == this.orgList[i].orgId) {
          return this.orgList[i].orgName
        }
      }
      return ''
    },
    setFormEmpty() {
      this.form = {
        username: undefined,
        realName: undefined,
        password: undefined,
        isValid: undefined,
        mobile: undefined,
        orgId: undefined,
        remark: undefined,
        status: undefined,
        role: []
      }
    },
    handleBatchDeleteDict() {
      const accountList = this.$refs.multipleTable.selection
      if (accountList.length > 0) {
        this.$confirm('此操作将删除选中的账号', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          for (let i = 0; i < accountList.length; i++) {
            delObj(accountList[i].userId)
          }
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }).catch(() => {

        })
      } else {
        this.$message({
          message: '请勾选要删除的账号',
          type: 'warning'
        })
      }
    },
    updateStatus(obj, status) {
      obj.status = status
      putObj(obj).then(async() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      }).catch(() => {

      })
    }
  }
}
</script>


<style lang='scss' scoped>
.w347 {
  width: 100%;
}
</style>
